package com.heima.app.gateway.filter;

import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 目标：获取请求头上的面token，使用JWT进行校验，校验通就放行，校验不同就阻止

        // 1. 获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        if (path.contains("/login")) {
            return chain.filter(exchange);
        }

        // 2. 获取请求头上的token
        String token = request.getHeaders().getFirst("token");

        // 3. 检查token是否有效
        boolean verify = JWTUtil.verify(token, "heimaleadnews".getBytes());

        // 4. 如果验证失败，则阻止请求，并返回401
//        if (!verify) {
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
//        }

        // 5.如果成功则放行
        return chain.filter(exchange);
    }
}